<template>
  <div>
    <!-- 主列表页面 -->
    <div v-if="!showEditPage">
      <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
        <a-row
          class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden"
        >
          <!-- 查询条件 -->
          <a-row v-if="showSearchRow" class="w-full">
            <a-form
              :model="searchForm"
              label-align="left"
              layout="inline"
              size="small"
            >
              <a-form-item field="purchaseIndexRecordCode" label="编号">
                <a-input
                  v-model="searchForm.purchaseIndexRecordCode"
                  allow-clear
                  placeholder="请输入编号"
                />
              </a-form-item>
              <a-form-item field="purchaseTimeRange" label="购买时间">
                <a-range-picker
                  v-model="searchForm.purchaseTimeRange"
                  show-time
                  format="YYYY-MM-DD HH:mm:ss"
                  allow-clear
                />
              </a-form-item>
            </a-form>
            <a-row class="w-full mt-2" justify="center">
              <a-space>
                <a-button
                  v-perm="['lindi:purchaseIndexRecord:get']"
                  type="primary"
                  @click="getPageList(false)"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <template #default>查询</template>
                </a-button>
                <a-button @click="getPageList(true)">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <template #default>重置</template>
                </a-button>
              </a-space>
            </a-row>
          </a-row>

          <!-- 分割线 -->
          <a-divider v-if="showSearchRow" class="mt-2" />

          <!-- 数据操作区 -->
          <a-row class="w-full flex justify-between">
            <a-space>
              <!-- 添加 -->
              <a-button
                v-perm="['lindi:purchaseIndexRecord:add']"
                size="small"
                type="primary"
                @click="handleAdd"
              >
                <template #icon>
                  <icon-plus />
                </template>
                <template #default>新增</template>
              </a-button>
            </a-space>
            <a-space>
              <!-- 刷新 -->
              <a-button shape="circle" size="small" @click="getPageList(false)">
                <template #icon>
                  <icon-refresh />
                </template>
              </a-button>
              <!-- 收缩/展开 -->
              <a-button
                shape="circle"
                size="small"
                @click="showSearchRow = !showSearchRow"
              >
                <template #icon>
                  <icon-caret-up v-if="showSearchRow" />
                  <icon-caret-down v-else />
                </template>
              </a-button>
            </a-space>
          </a-row>

          <!-- 数据展示区 -->
          <a-row class="w-full flex-1 mt-3 overflow-y-auto">
            <a-table
              :columns="datatable.columns"
              :data="datatable.records"
              :loading="datatable.loading"
              :pagination="false"
              :row-key="'recordId'"
              :scroll="{ minWidth: 600, y: '100%' }"
              class="w-[100%]"
              table-layout-fixed
            >
              <!-- 编号列模板 -->
              <template #purchaseIndexRecordCode="{ record }">
                <a-link icon @click="handleDetail(record.purchaseIndexRecordId)">
                  {{ record.purchaseIndexRecordCode }}
                </a-link>
              </template>
              <!-- 购买信息列模板 -->
              <template #purchaseInfo="{ record }">
                <span
                  v-if="record.purchaseItems && record.purchaseItems.length > 0"
                >
                  <div
                    v-for="(item, index) in record.purchaseItems"
                    :key="index"
                    class="mb-1"
                  >
                    {{ item.townName }}:{{ item.townIndex }}亩
                  </div>
                </span>
                <span v-else>-</span>
              </template>
              <!-- 审批单位列模板 -->
              <template #approvalUnit="{ record }">
                <span>林业局</span>
              </template>
              <!-- 操作 -->
              <template #operation="{ record }">
                <a-button
                  v-perm="['lindi:purchaseIndexRecord:update']"
                  size="mini"
                  type="text"
                  @click="handleEdit(record)"
                >
                  <template #icon>
                    <icon-edit />
                  </template>
                  <template #default>修改</template>
                </a-button>
                <a-popconfirm
                  :content="`确定删除编号【${record.purchaseIndexRecordCode}】的记录吗?`"
                  type="warning"
                  @ok="onDeleteOK(record.purchaseIndexRecordId)"
                >
                  <a-button
                    v-perm="['lindi:purchaseIndexRecord:delete']"
                    :loading="
                      operationLoading.deleting[record.purchaseIndexRecordId]
                    "
                    size="mini"
                    status="danger"
                    type="text"
                  >
                    <template #icon>
                      <icon-delete />
                    </template>
                    <template #default>删除</template>
                  </a-button>
                </a-popconfirm>
              </template>
            </a-table>
          </a-row>

          <!-- 分页 -->
          <a-row class="w-full flex justify-end mt-2">
            <pagination
              v-if="datatable.total > 0"
              v-model:page-num="searchForm.pageNum"
              v-model:page-size="searchForm.pageSize"
              :total="datatable.total"
              @pagination="getPageList(false)"
            />
          </a-row>
        </a-row>
      </a-card>
    </div>

    <!-- 编辑页面 -->
    <div v-if="showEditPage">
      <component
        :is="PurchaseIndexRecordEdit"
        :params="editParams"
        @cancel="handleEditCancel"
        @ok="handleEditOk"
      />
    </div>

    <!-- 模态框 -->
     <a-modal
        v-model:visible="modal.visible"
        :esc-to-close="false"
        :footer="false"
        :mask-closable="false"
        draggable
        width="auto"
        :style="{ maxWidth: '90vw', minWidth: '600px' }"
      >
      <template #title>{{ modal.title }}</template>
      <component
        :is="modal.component"
        v-if="modal.visible"
        :params="modal.params"
        @cancel="onCancel"
        @ok="onOk"
      />
    </a-modal>
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, defineAsyncComponent, shallowRef } from "vue";
import {
  deletePurchaseIndexRecordByPurchaseIndexRecordIdApi,
  getPagePurchaseIndexRecordListApi,
} from "~/api/lindi/purchaseIndexRecord";
import PurchaseIndexRecordDetail from "./PurchaseIndexRecordDetail.vue";

// 动态导入组件
const PurchaseIndexRecordEdit = defineAsyncComponent(() =>
  import("./PurchaseIndexRecordEdit.vue")
);

// 全局实例
const { proxy } = getCurrentInstance();

// 是否展示搜索区域
const showSearchRow = ref(true);

// 编辑页面显示状态
const showEditPage = ref(false);
const editParams = ref({});

// 公共模态框
const modal = reactive({
  // 是否显示
  visible: false,
  // 模态框标题
  title: "购买指标记录管理",
  // 宽度
  width: "50%",
  // 传递参数
  params: {},
  // 组件名称
  component: null,
});

// 搜索参数表单
const searchForm = reactive({
  // 编号
  purchaseIndexRecordCode: null,
  // 购买时间范围
  purchaseTimeRange: null,
  // 页码
  pageNum: 1,
  // 条数
  pageSize: 10,
});

// 数据列表
const datatable = reactive({
  // 列配置
  columns: [
    { title: "编号", dataIndex: "purchaseIndexRecordCode", slotName: "purchaseIndexRecordCode", align: "center" },
    { title: "购买时间", dataIndex: "purchaseTime", align: "center" },
    {
      title: "购买信息",
      dataIndex: "purchaseInfo",
      slotName: "purchaseInfo",
      align: "center",
      width: 200,
    },
    {
      title: "审批单位",
      dataIndex: "approvalUnit",
      slotName: "approvalUnit",
      align: "center",
      width: 120,
    },
    {
      title: "备注",
      dataIndex: "remark",
      align: "center",
      ellipsis: true,
      tooltip: true,
    },
    {
      title: "操作",
      dataIndex: "operation",
      slotName: "operation",
      align: "center",
      width: 160,
      fixed: "right",
    },
  ],
  // 数据记录
  records: [],
  // 数据总数
  total: 0,
  // 加载状态
  loading: false,
});

// 操作loading状态
const operationLoading = reactive({
  // 删除loading状态，使用记录ID作为key
  deleting: {},
});

// 获取分页数据
const getPageList = (isReset) => {
  // 是否重置查询条件
  if (isReset) {
    searchForm.purchaseIndexRecordCode = null;
    searchForm.purchaseTimeRange = null;
    searchForm.pageNum = 1;
  }

  datatable.loading = true;

  // 准备请求参数
  const params = { ...searchForm };

  // 处理时间范围参数
  if (
    searchForm.purchaseTimeRange &&
    searchForm.purchaseTimeRange.length === 2
  ) {
    params.purchaseTimeStart = searchForm.purchaseTimeRange[0];
    params.purchaseTimeEnd = searchForm.purchaseTimeRange[1];
  }
  delete params.purchaseTimeRange;

  getPagePurchaseIndexRecordListApi(params)
    .then((res) => {
      datatable.records = res.records;
      datatable.total = res.total;
    })
    .catch((error) => {
      proxy.$message.error("获取购买指标记录列表失败: " + error.message);
      datatable.records = [];
      datatable.total = 0;
    })
    .finally(() => {
      datatable.loading = false;
    });
};

// 新增
function handleAdd() {
  editParams.value = {};
  showEditPage.value = true;
}

// 查看详情
function handleDetail(purchaseIndexRecordId) {
  modal.visible = true;
  modal.title = "查看购买指标记录详情";
  modal.params = {
    operationType: proxy.operationType.detail.type,
    purchaseIndexRecordId: purchaseIndexRecordId,
  };
  modal.component = shallowRef(PurchaseIndexRecordDetail);
}

// 查看
function handleView(record) {
  // 查看功能暂时保留原有逻辑，可以后续改为详情页面
  proxy.$message.info("查看功能待实现");
}

// 编辑
function handleEdit(record) {
  editParams.value = { purchaseIndexRecordId: record.purchaseIndexRecordId };
  showEditPage.value = true;
}

// 单个删除确认
function onDeleteOK(id) {
  operationLoading.deleting[id] = true;

  deletePurchaseIndexRecordByPurchaseIndexRecordIdApi(id)
    .then(() => {
      proxy.$message.success("删除成功");
      getPageList(false);
    })
    .catch((error) => {
      proxy.$message.error("删除失败: " + error.message);
    })
    .finally(() => {
      operationLoading.deleting[id] = false;
    });
}

// 编辑页面取消
function handleEditCancel() {
  showEditPage.value = false;
  editParams.value = {};
}

// 编辑页面确认
function handleEditOk() {
  showEditPage.value = false;
  editParams.value = {};
  // 刷新列表
  getPageList(false);
}

// 模态框确认
const onOk = () => {
  modal.visible = false;
  // 刷新列表
  getPageList(false);
};

// 模态框取消
const onCancel = () => {
  modal.visible = false;
};

// 初始加载数据
getPageList(true);
</script>
